# 数据库操作路由
from fastapi import APIRouter, Query, HTTPException
from typing import List, Optional, Any
from app.services.db_service import DatabaseService
import logging

router = APIRouter(prefix="/api/v1/db", tags=["database"])
db_service = DatabaseService()
logger = logging.getLogger(__name__)

@router.get("/execute_query", summary="执行SQL查询")
async def execute_query(
    query: str = Query(..., description="SQL查询语句"),
    params: Optional[str] = Query(None, description="参数（JSON格式字符串）")
):
    """
    执行SQL查询操作
    
    - **query**: SQL查询语句（必填）
    - **params**: 查询参数，JSON格式字符串（可选）
    """
    try:
        # 解析参数
        parsed_params = None
        if params:
            import json
            try:
                parsed_params = json.loads(params)
                # 确保参数是列表或元组
                if not isinstance(parsed_params, (list, tuple)):
                    parsed_params = [parsed_params]
            except json.JSONDecodeError:
                raise HTTPException(status_code=400, detail="参数格式错误，请提供有效的JSON格式字符串")
        
        # 执行查询
        result = db_service.execute_query(query, parsed_params)
        
        if result["success"]:
            return result
        else:
            raise HTTPException(status_code=500, detail=result.get("error", "查询失败"))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"执行查询时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=f"内部错误: {str(e)}")

@router.get("/execute_update", summary="执行SQL更新操作")
async def execute_update(
    query: str = Query(..., description="SQL更新语句（INSERT、UPDATE、DELETE等）"),
    params: Optional[str] = Query(None, description="参数（JSON格式字符串）")
):
    """
    执行SQL更新操作（INSERT、UPDATE、DELETE等）
    
    - **query**: SQL更新语句（必填）
    - **params**: 更新参数，JSON格式字符串（可选）
    """
    try:
        # 解析参数
        parsed_params = None
        if params:
            import json
            try:
                parsed_params = json.loads(params)
                # 确保参数是列表或元组
                if not isinstance(parsed_params, (list, tuple)):
                    parsed_params = [parsed_params]
            except json.JSONDecodeError:
                raise HTTPException(status_code=400, detail="参数格式错误，请提供有效的JSON格式字符串")
        
        # 执行更新
        result = db_service.execute_update(query, parsed_params)
        
        if result["success"]:
            return result
        else:
            raise HTTPException(status_code=500, detail=result.get("error", "更新失败"))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"执行更新时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=f"内部错误: {str(e)}")